package com.hcxny.chat

import android.app.Service
import android.content.Intent
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.Binder
import android.os.IBinder
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream
import java.io.OutputStream
import java.util.*

class MusicService : Service() {
    override fun onBind(p0: Intent?): IBinder? {
        return binder
    }

    private var musicMsg: MusicMsg? = null

    inner class MyBinder : Binder() {

        public fun getService(): MusicService {
            return this@MusicService
        }
    }

    private lateinit var mPlayer: MediaPlayer
    private val binder: MyBinder = MyBinder()

    override fun onCreate() {
        super.onCreate()

        mPlayer = MediaPlayer()
    }

    public fun download(msg: MusicMsg) {
        val path: String = "${applicationContext.filesDir}${File.pathSeparator}${UUID.randomUUID()}"
        CoroutineScope(Dispatchers.IO).launch {
            val inputStream = Requester.chatService.download(msg.musicSrc).byteStream()
            val byteArray: ByteArray = ByteArray(2048)
            val outputStream: OutputStream = FileOutputStream(path)
            while (true) {
                val readLen = inputStream.read(byteArray)
                if (readLen > -1) {
                    outputStream.write(byteArray, 0, readLen)
                } else {
                    break
                }
            }
            outputStream.flush()
        }
    }

    public fun play(msg: MusicMsg) {
        mPlayer.reset()
        mPlayer.setDataSource(msg.musicSrc)
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC)
        mPlayer.prepareAsync()
        mPlayer.setOnPreparedListener {
            mPlayer.seekTo(msg.musicStartTime)
            mPlayer.start()
        }
    }

    public fun stop() {
        mPlayer.stop()
    }
}